package fr.gdi.android.news.api.share;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;

public abstract class AbstractContactShareActivity extends AbstractShareActivity
{
    
    private static final int CONTACT_PICKER_RESULT = 1001;

    public AbstractContactShareActivity()
    {
        super();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        findViewById(getPickContactButtonId()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0)
            {
                pickContact();
            }
        });
    }

    protected abstract int getPickContactButtonId();
    
    protected abstract int getContactEditorId();

    private void pickContact()
    {
        Intent contactPickerIntent =  new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        contactPickerIntent.setType(getContactType()); 
        startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);  
    }

    protected abstract String getContactType();

    protected abstract Cursor getCursor(Intent data);
    
    protected abstract String getContactData(Cursor cursor);
        
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CONTACT_PICKER_RESULT:
                    Cursor cursor = getCursor(data);
                    if (cursor.moveToFirst()) {
                        String email = getContactData(cursor);
                        EditText contactEntry = (EditText) findViewById(getContactEditorId());  
                        contactEntry.setText(email); 
                    }
                    break;
            }
    
        } else {
            // gracefully handle failure
            //Log.w(DEBUG_TAG, "Warning: activity result not ok");
        }
    }

    protected String getRecipient()
    {
        return ((EditText) findViewById(getContactEditorId())).getText().toString();
    }
    
}